package org.rcy.ruicingmarket.security;

import org.rcy.framework.api.security.UserPrincipal;
import org.rcy.framework.security.authentication.AuthenticationToken;
import org.rcy.ruicingmarket.resource.ResourceGroup;
import org.rcy.ruicingmarket.oss.user.OssUser;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collection;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/10/27 11:59
 */


public class SecurityUserContext {

	/**
	 * 获取OSS当前登录的用户
	 * @return
	 */
	public static OssUser getOssUser(){
		UserPrincipal principal = getAuthentication() == null ? null : getAuthentication().getPrincipal();
		if (principal == null) {
			return null;
		}
		return (OssUser)principal;
	}

	public static Collection<ResourceGroup> getUserResourceGroups(){
		UserPrincipal principal = getAuthentication() == null ? null : getAuthentication().getPrincipal();
		if (principal == null) {
			return null;
		}
		OssUser user = (OssUser)principal;
		return user.getResourceGroups();
	}

	private static AuthenticationToken getAuthentication(){
		SecurityContext securityContext = SecurityContextHolder.getContext();
		if (!(securityContext.getAuthentication() instanceof AuthenticationToken)) {
			return null;
		}
		AuthenticationToken authentication = (AuthenticationToken) securityContext.getAuthentication();

		if (authentication == null) {
			return null;
		}
		return authentication;
	}

	public static Collection<SimpleGrantedAuthority> getAuthorities(){
		SecurityContext securityContext = SecurityContextHolder.getContext();
		if (!(securityContext.getAuthentication() instanceof AuthenticationToken)) {
			return null;
		}
		AuthenticationToken authentication = (AuthenticationToken) securityContext.getAuthentication();

		if (authentication == null) {
			return null;
		}
		return (Collection<SimpleGrantedAuthority>) authentication.getAuthorities();
	}

	public static void refreshOssUser(OssUser user){
		SecurityContext securityContext = SecurityContextHolder.getContext();
		if (!(securityContext.getAuthentication() instanceof AuthenticationToken)) {
			return;
		}
		AuthenticationToken authentication = (AuthenticationToken) securityContext.getAuthentication();
		if (authentication == null) {
			return;
		}
		//修改密码后同步刷新缓存中的信息
		String csrfToken = authentication.getCsrfToken();
		String statelessToken = authentication.getStatelessToken();
		authentication = new AuthenticationToken(user,authentication.getAuthorities(),null);
		authentication.setCsrfToken(csrfToken);
		authentication.setStatelessToken(statelessToken);
	}

}
